package com.bgybmi.interceptor;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpSession;

import com.bgybmi.common.Constants;
import com.bgybmi.entity.Users;
import com.bgybmi.util.Utility;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.qyweixin.sdk.api.OAuthApi;

public class OAuth2Interceptor implements Interceptor{

	@Override
	public void intercept(Invocation inv) {
		// TODO Auto-generated method stub
		Controller controller = inv.getController();
		Users u = Constants.getLoginUser(controller.getSession());
        if (!Utility.empty(u))
        {
            inv.invoke();
        }
        else
        {
        	//验证
            String redirectionUrl ="http://" + controller.getRequest().getServerName() +controller.getRequest().getContextPath();
            String res=oAuthRedirect(redirectionUrl);
            //controller.getRequest().getRequestDispatcher(res);//重定向到我们已经的url  转发重定向，然后携带参数回来
            try {
				controller.getResponse().sendRedirect(res);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
	}
	
	/**
	 * @return    redirect_uri?code=CODE&state=STATE
	 */
	public static String oAuthRedirect(String redirect_uri){
		//String url = "http://" + getRequest().getServerName() + getRequest().getContextPath();
				//+ getRequest().getServletPath();
				//+ getRequest().getServletPath();
		System.out.println("我的url是:" + redirect_uri);
		//String redirect_uri = null;
		String codeUrl = null;
		try {
			redirect_uri = URLEncoder.encode(redirect_uri, "utf-8");
			codeUrl = OAuthApi.getCodeUrl(redirect_uri,PropKit.get("corpId"));
			//redirect(codeUrl);	
			//调用之后发生转向
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return codeUrl;
	}
}
